package com.taiji.dicom4cloud.smart.alarm.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.taiji.dicom4cloud.common.core.constrant.CommonConstants;
import com.taiji.dicom4cloud.smart.alarm.annoation.HandlerType;
import com.taiji.dicom4cloud.smart.alarm.common.EnumHandler;
import com.taiji.dicom4cloud.smart.alarm.common.MessageHandler;
import com.taiji.dicom4cloud.smart.alarm.model.Message;
import com.taiji.dicom4cloud.smart.alarm.utils.AlarmUtils;
import com.taiji.dicom4cloud.smart.model.entity.AlarmEquipment;
import com.taiji.dicom4cloud.smart.model.entity.RfidRecord;
import com.taiji.dicom4cloud.smart.rfid.config.MqttGatewayService;
import com.taiji.dicom4cloud.smart.service.AlarmEquipmentService;
import com.taiji.dicom4cloud.smart.service.AlarmRecordService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/8/23
 **/
@HandlerType(value = EnumHandler.BREAK_DOWN)
public class BreakDownHandler implements MessageHandler {
    @Autowired
    private AlarmEquipmentService alarmEquipmentService;
    @Autowired
    private AlarmRecordService alarmRecordService;
    @Autowired
    private MqttGatewayService mqttGatewayService;

    @Override
    public Object handle(Message message) {

        AlarmEquipment alarmEquipment = alarmEquipmentService.getByEquipmentId(message.getEquipmentId());
        if(ObjectUtil.isNotNull(alarmEquipment)){
            alarmEquipment.setIsNormal(CommonConstants.IsNormal.ERROR);
            alarmEquipment.setIsAlarm(CommonConstants.IsAlarm.ALARM);
            alarmEquipment.setReportTime(LocalDateTime.now());
            alarmEquipmentService.updateById(alarmEquipment);

            RfidRecord record = new RfidRecord();
            BeanUtil.copyProperties(alarmEquipment,record);
            record.setEquipmentName(alarmEquipment.getAlarmEquipmentName());
            BeanUtil.copyProperties(message,record);
            byte[]data = message.getData();
            record.setAlarmType( AlarmUtils.getTypeShort(data));
            record.setAlarmName(AlarmUtils.getAlarmName(data));
            record.setAlarmTime(LocalDateTime.now());
            record.setCreateTime(LocalDateTime.now());
            record.setIsAlarm(CommonConstants.IsAlarm.ALARM);
            record.setType(CommonConstants.EquipmentType.electricMeter);
            alarmRecordService.saveRecord(record);

            mqttGatewayService.send2Mqtt("alarm.rfid", JSONObject.toJSONString(record));

        }
        return null;
    }
}
